// import { useEffect, useRef } from 'react'
import ArticleItem from '../ArticleItem'
import { InfiniteScroll, PullToRefresh } from 'antd-mobile'
import styles from './index.module.scss'
import { getArticleListAsync } from '@/store'
import { useAppDispatch, useAppSelector } from '@/store'
import { useNavigate } from 'react-router-dom'

interface Props {
  channelId: number
}

function ArticleList({ channelId }: Props) {
  const dispatch = useAppDispatch()
  const navigate = useNavigate()

  const {
    channelArticles: { [channelId]: channelArticle }
  } = useAppSelector((state) => state.homeSlice)

  // const renderRef = useRef(true)
  // async function execDispatch() {
  //   renderRef.current = false
  //   await dispatch(getArticleListAsync({ channel_id: channelId, timestamp: Date.now() }, 'push'))
  //   renderRef.current = true
  // }
  // useEffect(() => {
  //   // 仅第一次加载页面没有频道数据的时候执行
  //   if (renderRef.current && !channelArticle) {
  //     execDispatch()
  //   }
  // }, [dispatch, channelId])
  const { results: articles = [], pre_timestamp } = channelArticle || {}

  // 有时间戳，并且缓存数据不能超过100，才允许加载更多
  const hasMore = pre_timestamp !== null && articles.length <= 100
  async function loadMore() {
    await dispatch(
      getArticleListAsync({ channel_id: channelId, timestamp: pre_timestamp || Date.now() }, 'push')
    )
  }
  // 下拉刷新
  async function onRefresh() {
    await dispatch(getArticleListAsync({ channel_id: channelId, timestamp: Date.now() }, 'reset'))
  }
  return (
    <div className={styles.root}>
      {/* 文章列表中的每一项 */}
      <PullToRefresh onRefresh={onRefresh}>
        {articles.map((item) => (
          <div className="article-item" key={item.art_id} onClick={() => navigate(`/article/${item.art_id}`)}>
            <ArticleItem article={item} />
          </div>
        ))}
        {/* 无限加载组件 */}
        <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
      </PullToRefresh>
    </div>
  )
}

export default ArticleList
